package com.qxcy.gzy.util;

import android.os.Environment;
import android.text.TextUtils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class LocalLogUtils {
    public static void saveLocalLog(String title, String message, String path) {
        try {
            String time = new SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.CHINA).format(new Date());
            String fileName = title + "-" + time + ".txt";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                FileUtils.createDir(path);
                File file = getLogFile(path, fileName);
                //追加写入内容
                addTxtToFileBuffered(file, message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void saveLocalDailyLog(Date date, String message, String path) {
        if (TextUtils.isEmpty(message)) message = "";
        if (TextUtils.isEmpty(path)) path = ConstantCore.FILE_ROOT_PATH;
        try {
            //检查是否存在今天的日志文件，以日期为名
            String timeAll = new SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.CHINA).format(date);
            message = message + "******" + timeAll;
            String time = new SimpleDateFormat("yyyyMMdd", Locale.CHINA).format(date);
            String fileName = time + ".txt";
            //文件夹检查，不存在则创建
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                //文件夹
                File dir = new File(path);
                if (!dir.exists()) {
                    boolean isSuccess = dir.mkdirs();
                    System.out.println(isSuccess);
                }
            }
            //文件不存在则创建
            File file = getSupportAttachFile(path, fileName, false, 0);
            //追加写入内容
            addTxtToFileBuffered(file, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static File getLogFile(String path, String fileName) {
        String fullName = path + File.separator + fileName;
        File file = new File(path, fileName);
        if (!FileUtils.fileIsExists(fullName)) {
            FileUtils.createNewFile(path, fileName);
        }
        return file;
    }

    /**
     * 检测文件大小，超过限制，分文件生成
     *
     * @param path      文件夹路径
     * @param fileName  文件名
     * @param isSupport 是否支持超额分文件存储
     * @param limitSize isSupport为true是值为文件大小上限，单位为MB,默认为10
     */
    private static File getSupportAttachFile(String path, String fileName, boolean isSupport, int limitSize) {
        String fullName = path + File.separator + fileName;
        File file = new File(path, fileName);
        if (!FileUtils.fileIsExists(fullName)) {
            FileUtils.createNewFile(path, fileName);
        } else {
            if (isSupport) {
                limitSize = (limitSize <= 1 || limitSize >= 100) ? 10 : limitSize;
                //检测文件是否超额
                double fileSize = FileSizeUtil.getFileOrFilesSize(fullName, FileSizeUtil.SIZE_TYPE_MB);
                //超额份文件
                if (fileSize > limitSize) {
                    int i = 1;
                    String attachFileName = fileName + "_" + i;
                    String attachFileFullName = path + File.separator + attachFileName;
                    while (FileUtils.fileIsExists(attachFileFullName)) {
                        //检测分文件是否超额
                        double attachFileSize = FileSizeUtil.getFileOrFilesSize(fullName, FileSizeUtil.SIZE_TYPE_MB);
                        if (attachFileSize > limitSize) {
                            i++;
                            attachFileName = fileName + "_" + i;
                            attachFileFullName = path + File.separator + attachFileName;
                        } else {
                            return new File(attachFileFullName);
                        }
                    }
                    //已经存在的分文件都已超额，需要重新创建
                    File attachFile = new File(attachFileFullName);
                    FileUtils.createNewFile(path, attachFileName);
                    return attachFile;
                }
            }
        }
        return file;
    }

    /**
     * 使用BufferedWriter进行文本内容的追加
     *
     * @param file    文件
     * @param content 内容
     */

    private static void addTxtToFileBuffered(File file, String content) {
        //在文本文本中追加内容
        BufferedWriter out = null;
        try {
            //FileOutputStream(file, true),第二个参数为true是追加内容，false是覆盖
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
            out.newLine();//换行
            out.write(content);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 使用FileWriter进行文本内容的追加
     *
     * @param file    文件
     * @param content 内容
     */
    private static void addTxtToFileWrite(File file, String content) {
        FileWriter writer = null;
        try {
            //FileWriter(file, true),第二个参数为true是追加内容，false是覆盖
            writer = new FileWriter(file, true);
            writer.write("\r\n");//换行
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}